package com.ksl.kinglockguard.service;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.activity.GameListActivity;
import com.ksl.kinglockguard.bitmap.ImageLoader;
import com.ksl.kinglockguard.bitmap.ImageLoader.ILoadedFinishLister;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.domain.H5List;
import com.ksl.kinglockguard.domain.H5News;
import com.ksl.kinglockguard.domain.MainList;
import com.ksl.kinglockguard.domain.MainNews;
import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.utils.ImageUtils;
import com.ksl.kinglockguard.utils.KingsSystemUtils;
import com.ksl.kinglockguard.utils.SdcardFileUtil;
import com.ksl.kinglockguard.utils.ShortcutUtil;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;
import com.lsk.open.core.net.NetConnectTask.TaskListener;
import com.lsk.open.core.net.NetHeadUtils;
import com.lsk.open.core.serialize_cache.CacheDataManager;
import com.lsk.open.core.utils.KingsFileUtils;
import com.lsk.open.core.utils.ProductInfoUtils;

public class TimeRunableService extends IntentService {
	

	private static int RQ_TIME = 10* 60 * 1000;
//	private static int RQ_TIME = 1 * 1000;
	private static long mRq_time = RQ_TIME;
	private static int RANDOMTIME = 5 * 60 * 60 * 1000;
	private static int H5_GAME_SWITHER_DAYS = 0;//todo ydy 桌面小游戏开关 时间控制
	public static final String SHOW_SMALL_IMAGE = "1";
	private static final int REQUEST_NUM = 20;
	public MainList screenNews;
	private int mDowloadPicIndex = -1;// 用于保存正在交替数据两批数据脚标
	private Context mContext;

	private List<MainNews> mDowloadingList;// 保存正在下载列表
	private boolean isLoadedAll;

	private boolean isLoadChecked = false;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1){
				H5News mNews = (H5News)msg.obj;
				if(mNews != null){
					ShortcutUtil.createShortCut(TimeRunableService.this,mNews);
					//被动生成h5游戏快捷方式数据统计
					UserCountHabit.setUserCount(TimeRunableService.this, UserCountHabit.H5_NEGATIVE_ADD_SHORTCUT_NUM+mNews.getId());
					//将游戏的id存入sharepreference
					String saveId = "$"+String.valueOf(mNews.getId())+"$";
					String idStr = SharePreferenceSdkData.getShortcutProducedBefore(mContext)+","+saveId;
					SharePreferenceSdkData.setShortcutProducedBefore(mContext, idStr);
				}
			}
			
		};
	};
	
	public TimeRunableService() {
		super("TimeRunableService");
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		MyLog.i("jyh5", "~~~~~~TimeRunableService onCreate~~~~");
		mContext = getApplicationContext();
	}
	
	private void setAlarm(){
		AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		PendingIntent intent = PendingIntent.getService(this, 0, new Intent(this, TimeRunableService.class), 0);
		alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+mRq_time, intent);
	}
	@Override
	protected void onHandleIntent(Intent intent) {	
	
		
		MyLog.i("jyh5", "~~~~~~onHandleIntent~~~~");
		long now = System.currentTimeMillis();
		
		//同步后台锁屏开关，是否打开锁屏（24小时1次）
		NetworkTask.requestScreenLockFlag(mContext);
		
		//请求锁屏资源或是图片资源
		loadLockAdOrPicture();
		
		MyLog.i("jyh5", "~~~~~~loadLockAdOrPicture after~~~~");
		//同步用户信息,包括用户的IP地址，阅读兴趣等(每7天1次)
		if(now - SharePreferenceSdkData.getUserProfileUpdateTime(mContext) > 7 * 24 * 60 * 60 * 1000){
			NetworkTask.requestUserProfile(mContext);
		}

		// 与服务器同步锁屏咨询显示策略，包括h5游戏icon的显示策略等
		if (now - SharePreferenceSdkData.getLastSyncStrategyTime(mContext) > 12 * 60 * 60 * 1000) {
			MyLog.i("wmm", "syncScreenLockStrategy");
			NetworkTask.syncScreenLockStrategy(mContext);
		}
		
		//向服务器同步H5页面的最新数据(12小时一次)
		if (now - SharePreferenceSdkData.getH5UpdateTime(mContext) > 12 * 60 * 60 * 1000) {//修改更新时间  调整12小时 目前有点浪费流量 ydy
			if (NetHeadUtils.isNetWorking(getApplicationContext())) {
  				RequestH5GameList();//服务器下发weight+10个游戏资讯
  				SharePreferenceSdkData.setH5UpdateTime(mContext, now);
			}
		}
		
		//重新生成桌面小游戏快捷方式(每15天1次)
		if(now - SharePreferenceSdkData.getGameIconUpdateTime(mContext) > 15 * 24 * 60 * 60 * 1000){
			SharePreferenceSdkData.setIsShortCut(mContext, false);
			ShortcutUtil.createShortCut(mContext);
			SharePreferenceSdkData.setGameIconUpdateTime(mContext, now);
		}
		
		//上传用户行为统计数据(每12小时1次)
		NetworkTask.uploadUserCount(mContext);
		
		
		//活跃用户统计(每天上传)
		if (!KingsSystemUtils.isSameDay(SharePreferenceSdkData.getLastUploadLauncherTimes(mContext) )) {
			SharePreferenceSdkData.setLanucherTimers(mContext,System.currentTimeMillis());
			NetworkTask.requestLanuchMyApp(mContext);
		}
		
		setAlarm();
	}
	
	public void loadLockAdOrPicture(){
		
		//如果锁屏开关为关则执行
		if(!SharePreferenceSdkData.getScreenLockFlag(mContext))
			return;
		
		screenNews = (MainList) CacheDataManager
				.getListCacheOrLoadSeriaByKey(Constants.FSKEY_NEWlISTS);
		
		if (CacheDataManager
				.isDataValidate(Constants.FSKEY_NEWlISTS) == 0) {
			RequestLockscreenAd(REQUEST_NUM, screenNews == null ? 0
					: screenNews.getMaxID());
			setAlarm();
			return;
		}
		MyLog.i("ydy", "timeRunnable");
		isLoadedAll = SharePreferenceSdkData.isLoaded(mContext);
//		Toast.makeText(getApplicationContext(), "isLoadedAll : " + isLoadedAll, 1).show();
		MyLog.i("wmm", "isLoadedAll : "+isLoadedAll);
		long interval = SharePreferenceSdkData.getIntervalTime(mContext);
		long now = System.currentTimeMillis();
		long last = SharePreferenceSdkData.getLastRequestTime(mContext);
	
		boolean traversalSwitch = SharePreferenceSdkData
				.getTraversalSwitch(mContext);
		boolean condition = traversalSwitch ? isLoadedAll
				&& Math.abs(now - last) > interval
				: Math.abs(now - last) > interval;
		MyLog.i("wmm", "isLoadedAll " + isLoadedAll);
		if (condition && NetHeadUtils.isNetWorking(mContext)) {
			MyLog.i("ydy", "timeRunnable  RequestLockscreenAd");
			RequestLockscreenAd(REQUEST_NUM, screenNews == null ? 0
					: screenNews.getMaxID());
		} else {
			MyLog.i("ydy", "timeRunnable  loadCache");
			loadCache();
		}
	}
	
	//请求h5列表
    public void RequestH5GameList() {
		JSONObject request = new JSONObject();
		try {
			request.put("number", GameListActivity.GAME_NUMBER_FIXED);
            request.put("cat", Constants.ARTICLE_CAT_GAME);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
        String content = request.toString();
        Log.d("h5request", "------content: " + content);
        NetConnectTask netTask = NetworkTask.requestH5List(this, content);
		netTask.setListener(new TaskListener() {
			@Override
			public void onNoNetworking() {
                MyLog.d("jyh1", "-----------onNoNetworking ------ ");
			}
			@Override
			public void onNetworkingError() {
                MyLog.d("jyh1", "-----------onNetworkingError -----");
			}
			@Override
			public void onPostExecute(byte[] bytes) {
                MyLog.d("jyh1", "-----------onPostExecute: "+ new String(bytes));
				try {
					JSONObject result = new JSONObject(new String(bytes));
					String errno = result.getString("errno");
					if(result.isNull("data")){
						Toast.makeText(getApplicationContext(), R.string.H5_beyond_articles, Toast.LENGTH_SHORT).show();
						return;
					}
					JSONArray dataList = null;
					if(errno.equals("200")){
						dataList = result.getJSONArray("data");
						if(dataList != null){
							H5List h5NewsList = H5List.parse(dataList);
							CacheDataManager.deleteSeriaFile(Constants.H5_LIST);
							CacheDataManager.setListCacheAndWriteByKey(Constants.H5_LIST, h5NewsList);
							if(h5NewsList != null)
								createShortcut(h5NewsList);
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}
    
    private void createShortcut(H5List h5NewsList){
    	if(h5NewsList == null)
    		return;
    	for(H5News mNews:h5NewsList.getNewslist()){
    		MyLog.i("jyh4", "~~~~getGenerateDeskIconFlag~~~~"+mNews.getGenerateDeskIconFlag());
    		MyLog.i("jyh4", "~~~~getGameName~~~~"+mNews.getGameName());
    		MyLog.i("jyh4", "~~~~getIconUrl~~~~"+mNews.getIconUrl());
    		MyLog.i("jyh4", "~~~~getarticelUrl~~~~"+mNews.getArticleUrl());
    		String saveId = "$"+String.valueOf(mNews.getId())+"$";
    		boolean mFlag = SharePreferenceSdkData.getShortcutProducedBefore(mContext).contains(saveId);
    		if(mNews.getGenerateDeskIconFlag() == 1 && !mFlag)
    			downloadDeskIcon(mNews);
    		else{
    			ImageLoader imageLoader = ImageLoader.getInstance(mContext);
    			imageLoader.queuePhoto(mNews.getIconUrl(), null,Constants.LOCK_SHORT_CUT);
    		}
    	}
    }
    
    private void downloadDeskIcon(final H5News mNews){
    	File f = null;
		try {
			f = SdcardFileUtil.getFile(Constants.LOCK_SHORT_CUT, mNews.getIconUrl());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (f != null && f.exists()){
			Message message = new Message();
			message.obj=mNews;
			message.what=1;
			mHandler.sendMessageDelayed(message, 3*1000);
		}else{
	    	ImageLoader imageLoader = ImageLoader.getInstance(getApplicationContext());
			imageLoader.setmILoadedFinishLister(new ILoadedFinishLister() {
				
				@Override
				public void dowloadOk(String url) {
					Message message = new Message();
					message.obj=mNews;
					message.what=1;
					mHandler.sendMessageDelayed(message, 3*1000);
				}
			});
			imageLoader.queuePhoto(mNews.getIconUrl(), null,Constants.LOCK_SHORT_CUT);
		}
    }
	
	private void loadCache() {
		if (CacheDataManager.isDataValidate(Constants.FSKEY_NEWlISTS) == 2) {
			MyLog.i("ydy4",
					"ScreenLockService (CacheDataManager.isDataValidate)==2");
			screenNews = (MainList) CacheDataManager
					.getListCacheOrLoadSeriaByKey(Constants.FSKEY_NEWlISTS);
			if (screenNews != null && screenNews.getNewsCount() > 0) {
				LoadScreenImage(screenNews, false);
			} else {
				CacheDataManager
						.deleteSeriaFile(Constants.FSKEY_NEWlISTS);
			}
		} else {
			MyLog.i("ydy",
					"isDataValidate"
							+ CacheDataManager
									.isDataValidate(Constants.FSKEY_NEWlISTS));
			if (NetHeadUtils.isNetWorking(getApplicationContext())) {
				MyLog.e("ydy", "setTodayDeskPictureNum*************11111");
				Calendar now = Calendar.getInstance();
				int hour = now.get(Calendar.HOUR_OF_DAY);
				if (hour < 6 && mRq_time == RQ_TIME) {// 将请求服务器压力从２４点后五分钟内扩散到５个小时内，５点之后频率不变（这一块注意测试）
					Random r = new Random();
					int val = RANDOMTIME - hour * 60 * 60 * 1000;
					if (val > 0) {
						int random = r.nextInt(val);
						if (random <= 0 || random > RANDOMTIME) {
							random = 30 * 60 * 1000;
						}
						mRq_time = random;
						MyLog.i("wmm", "random  :  " + mRq_time);
					}
					MyLog.e("ydy", "hourtime===" + hour + "mRq_time=="
							+ mRq_time);
				} else {
					mRq_time = RQ_TIME;
					// 避免nullpointer
					RequestLockscreenAd(REQUEST_NUM, 0);// 请求20个广告
				}
			}
		}
	}
	
	private synchronized void RequestLockscreenAd(int adNums, int maxId) {
		MyLog.i("wmm", "RequestLockscreenAd");
		JSONObject request = new JSONObject();
		try {
			request.put("app_key", "391ef58892588b6c");
			request.put("small_img", "208x128");
			request.put("large_img", ProductInfoUtils
					.getScreenWithOrHeight(getApplicationContext()));

			request.put("number", adNums);
			if (maxId > 0) {
				request.put("max_id", maxId);
			}
			// request.put("lockscreen_show", 1);
			request.put("time", System.currentTimeMillis());
			// request.put("sign ", KingsSystemUtils.getSignature());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		NetConnectTask netTask = NetworkTask.requestMainPageList(this,
				request.toString());

		netTask.setListener(new TaskListener() {

			@Override
			public void onNoNetworking() {

			}

			@Override
			public void onNetworkingError() {

			}

			@Override
			public void onPostExecute(byte[] bytes) {
				MyLog.d("jyh", "requestScreenAd-----------onPostExecute: "
						+ new String(bytes));
				MainList newslist = null;
				try {
					JSONObject result = new JSONObject(new String(bytes));
					if (200 == result.getInt("errno")) {
						SharePreferenceSdkData.setLastRequestTime(
								getApplicationContext(),
								System.currentTimeMillis());
					}
					JSONArray dataList = result.optJSONArray("data");
					newslist = MainList.parse(dataList);
					// 服务器没有返回数据，不进行任何处理
					if (newslist.getNewsCount() == 0) {
						return;
					}

				} catch (IOException e) {
					e.printStackTrace();
					return;
				} catch (JSONException e) {
					e.printStackTrace();
					return;
				}

				// 如果服务器返回的有效数据小于20，则将本地的数据与新数据进行合并
				if (newslist.getNewsCount() < 20 && screenNews != null
						&& screenNews.getNewsCount() > 0) {
					List<MainNews> newNews = newslist.getNewslist();
					List<MainNews> oldNews = screenNews.getNewslist();
					for (MainNews news : oldNews) {
						boolean isContain = false;
						for (MainNews n : newNews) {
							if (news.getId() == n.getId()) {
								isContain = true;
								break;
							}
						}
						if (!isContain) {
							newNews.add(news);
						}
						if (newNews.size() >= 20) {
							break;
						}
					}
					newslist.setNewsCount(newNews.size());
				}
				if (newslist != null && newslist.getNewsCount() > 0)
					screenNews = newslist;
				if (screenNews != null && screenNews.getNewsCount() > 0) {
					LoadScreenImage(screenNews, true);
					SharePreferenceSdkData.setLastNewsIndex(getApplicationContext(), 0);
				}
			}
		});
	}
	
	private synchronized void LoadScreenImage(MainList mNews, boolean isUpdate) {
		int loadNum = mNews.getNewsCount();
		// 所用网络环境加载一样数目的图片
		if (!NetHeadUtils.getNetworkType(getApplicationContext()).equals("wifi")) {
			loadNum = 3;// 3g 2G及４G网络情况 //todo ydy
		}
		if (isLoadChecked
				&& !isUpdate
				&& SharePreferenceSdkData
						.getTodayDeskPictureNum(getApplicationContext()) == loadNum) {// 在同等待网络
			return;
		}
		MyLog.e("ydy", "ScreenLockService *****LoadScreenImage loadNum=="
				+ loadNum);
		if (isUpdate) {
			mDowloadPicIndex = SharePreferenceSdkData
					.getTodayDeskPictureIndex(getApplicationContext());
			SharePreferenceSdkData.setTodayDeskPictureNum(
					getApplicationContext(), -1);
			SharePreferenceSdkData.setTodayDeskPictureIndex(
					getApplicationContext(), -1);
			isLoadChecked = false;
		}
		mDowloadingList = mNews.getNewslist();
		int size = loadNum;

		ImageLoader imageLoader = ImageLoader
				.getInstance(getApplicationContext());
		imageLoader.setmILoadedFinishLister(new ILoadedFinishLister() {

			@Override
			public void dowloadOk(String url) {
				if (mDowloadingList != null) {
					for (int i = 0; i < mDowloadingList.size(); i++) {
						if (i >= mDowloadingList.size())
							break;
						String imageUrl = mDowloadingList.get(i)
								.getLargeImageUrl();
						if (null == imageUrl || imageUrl.equals("null")) {
							continue;
						} else {
							if (url.equalsIgnoreCase(imageUrl)) {
								
								int curIndex = SharePreferenceSdkData
										.getTodayDeskPictureIndex(getApplicationContext());
								if (i >= curIndex) {
									SharePreferenceSdkData
											.setTodayDeskPictureIndex(
													getApplicationContext(), i);// 记录脚标
									isLoadedAll = false;
								}
								if (i == mDowloadingList.size() - 1) {
									mDowloadPicIndex = -1;
								}
							}
						}
					}
				}
			}
		});

		int loadIndex = -1;
		int totalLoad = 0;
		for (int i = 0; i < mDowloadingList.size(); i++) {
			if (i >= mDowloadingList.size())
				break;
			String imageUrl = mDowloadingList.get(i).getLargeImageUrl();
			if (null == imageUrl || imageUrl.equals("null")) {
				if (size >= 3 && size < mDowloadingList.size()) {
					size++;
				}
				continue;
			}

			// String imageName = FileUtils.getFileName(imageUrl);
			// String filePath = Constants.FOLDER_PICTURE + File.separator
			// + imageName;
			// File file = new File(filePath);
			File file = null;
			try {
				file = SdcardFileUtil.getFile(
						ImageLoader.LOCK_SCREEN_PICTURE, imageUrl);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			MyLog.i("wmm", "file is exists " + file.exists());
			if (file.exists()) {
				loadIndex = i;
				totalLoad++;
				File blurfile = null;
				try {
					blurfile = SdcardFileUtil.getFile(
							ImageLoader.LOCK_BLUR_PICTURE, imageUrl);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!blurfile.exists()) {
					ImageUtils.makeBlurAndSaveFile(file,
							getApplicationContext());
				}

			} else {
				if (i < size) {// size主要控制wifi的下载
					MyLog.i("ydy",
							"ScreenLockService *****LoadScreenImage ******"
									+ imageUrl);
					imageLoader.queuePhoto(imageUrl, null,
							ImageLoader.LOCK_SCREEN_PICTURE);
				}
			}

			File smallImageFile = null;
			try {
				smallImageFile = SdcardFileUtil.getFile(
						ImageLoader.LOCK_DESK_ICON,
						mDowloadingList.get(i).getSmallImageUrl());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (!smallImageFile.exists()) {
				if (i < size) {
					// 判断news类型，是否下载
					if (SHOW_SMALL_IMAGE.equals(mDowloadingList.get(i)
							.getShowSmallImage())) {
						imageLoader.queuePhoto(mDowloadingList.get(i)
								.getSmallImageUrl(), null,
								ImageLoader.LOCK_DESK_ICON);
					}
				}
			}
		}

		if (loadIndex != -1 && !isUpdate) {
			isLoadChecked = true;
			SharePreferenceSdkData.setTodayDeskPictureIndex(
					getApplicationContext(), loadIndex);// 记录脚标
			SharePreferenceSdkData.setTodayDeskPictureNum(
					getApplicationContext(), totalLoad);// 记录已经加载过数据量
		}

		if (isUpdate) {
			MyLog.e("ydy", "ScreenLockService *****loadOK save seria file");
			CacheDataManager.deleteSeriaFile(Constants.FSKEY_NEWlISTS);
			CacheDataManager.setListCacheAndWriteByKey(
					Constants.FSKEY_NEWlISTS, mNews);
		}
	}
}
